package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.openai.models.evals.EvalCreateParams;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import static com.zzyl.common.core.domain.AjaxResult.success;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String IOT_ALL_PRODUCT_LIST= "iot:all_product_list";

    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode()!=200){
            throw new RuntimeException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        //保存到redis中
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }


    @Override
    public List<ProductVo> allProduct() {
        String list = String.valueOf(redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST));
        if (list==null){
            throw new RuntimeException("请先同步产品列表");
        }
        return JSONUtil.toList(list, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //设备名称是否重复
        long count = count(new LambdaQueryWrapper<Device>().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count>0){
            throw new RuntimeException("设备名称已存在");
        }
        //设备编号是否重复
        count = count(new LambdaQueryWrapper<Device>().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count>0){
            throw new RuntimeException("设备编号已存在");
        }
        //同一个位置是否有重复的产品
        count = count(new LambdaQueryWrapper<Device>()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(deviceDto.getPhysicalLocationType()!=null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()));

        if (count>0){
            throw new RuntimeException("同一个位置下有重复的产品");
        }

        //向华为iot注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        body.withProductId(deviceDto.getProductKey());
        body.withNodeId(deviceDto.getNodeId());

        // 秘钥设置,因为数据库表中也需要该字段
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        addDeviceRequest.setBody(body);

        AddDeviceResponse response;
        try {
            response = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        // 本地保存设备
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        // 秘钥
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        DeviceDetailVo deviceVo = new DeviceDetailVo();
        // 查询本地设备数据
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (device==null){
            return null;
        }
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        // 属性拷贝
        deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        // 日期转换
        if(activeTimeStr!=null) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            deviceVo.setActiveTime(activeTime);
        }
        return deviceVo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = client.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备影子，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (shadow.isEmpty()){
            return null;
        }

        // 获取上报数据的reported （参考返回的json数据）
        DeviceShadowProperties reported = shadow.get(0).getReported();
        Object properties = reported.getProperties();
        // 把数据转换为JSONObject(map)，方便处理
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        // 遍历数据，封装到list中
        List<Map<String,Object>>  list = new ArrayList<>();
        // 事件上报时间
        String eventTimeStr = reported.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = eventTime.format(formatter);


        // k:属性标识，v:属性值
        jsonObject.forEach((k,v) -> {
            Map<String,Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", format);
            list.add(map);
        });

        return list;
    }

    @Override
    public Boolean updateDevice(Device device) {
        //先判断是否只是修改设备名称
        Device one = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, device.getIotId()));
        //如果位置不变则只修改名称,如果位置改变则判断是否有重复
        if (one.getLocationType().equals(device.getLocationType())&&one.getRemark().equals(device.getRemark())){
            //- 先修改IoTDA平台上的设备名称
            updateHuawei(device);
            return updateById(device);
        }
        //- 注意：修改之后，不能在同一个位置绑定同一个产品
        //同一个位置是否有重复的产品
        long count = count(new LambdaQueryWrapper<Device>()
                        .eq(Device::getProductKey, device.getProductKey())
                        .eq(Device::getLocationType, device.getLocationType())
                        .eq(Device::getBindingLocation, device.getBindingLocation())
                        .eq(device.getPhysicalLocationType()!=null, Device::getPhysicalLocationType, device.getPhysicalLocationType()));
        if (count>0){
            throw new RuntimeException("同一个位置下有重复的产品");
        }

        // - 先修改IoTDA平台上的设备信息
        updateHuawei(device);
        // - 再修改本地存储的设备信息
        return updateById(device);
    }

    private void updateHuawei(Device device) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        request.withBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 修改设备名称，调用失败");
        }
    }

    @Override
    public Boolean removeDeviceById(String iotId) {
        //- 先从IoTDA平台删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        return remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if(StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云IOT平台接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
